package api

import (
	"demo/api/dto/request"
	"demo/api/dto/response"
	"demo/application/service"
	"demo/infra/middleware/auth"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type ConvertUrlHandler struct {
	convertUrlService *service.ConvertUrlService
	urlQueryService   *service.UrlQueryService
}

func NewConvertUrlHandler(convertUrlService *service.ConvertUrlService, urlQueryService *service.UrlQueryService) *ConvertUrlHandler {
	return &ConvertUrlHandler{convertUrlService: convertUrlService, urlQueryService: urlQueryService}
}

// CreateUrlPage 创建短链页面
func (rc ConvertUrlHandler) CreateUrlPage(c *gin.Context) {
	// 1. 通过认证中间件获取当前登录用户
	user, err := auth.GetCurrentContextUser(c)
	// 未登录用户访问（如果需要限制登录，可在这里判断并跳转）
	if err != nil {
		c.Redirect(http.StatusSeeOther, "/auth/login?redirect=/")
		return
	}
	c.HTML(http.StatusOK, "create.html", gin.H{
		"PageType": "create",
		"User":     user,
	})
}

// CreateUrlMap 创建短链
func (rc ConvertUrlHandler) CreateUrlMap(c *gin.Context) {
	var req request.CreateUrlMapRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
	}
	shortUrl := rc.convertUrlService.CreateUrlMap(c, req.LongUrl, req.Description, req.Source, req.Creator)
	c.JSON(http.StatusOK, response.Success(shortUrl))
}

// ReplaceUrlMap 替换短链
func (rc ConvertUrlHandler) ReplaceUrlMap(c *gin.Context) {
	var req request.ReplaceUrlMapRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
	}
	rc.convertUrlService.ReplaceUrlMap(c, req.Id, req.LongUrl, req.Description, req.Editor)
	c.JSON(http.StatusOK, response.Success(""))
}

// UrListPage 短链页面
func (rc ConvertUrlHandler) UrListPage(c *gin.Context) {
	// 1. 获取分页参数（默认第1页，每页10条）
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 50 { // 限制最大每页50条
		pageSize = 10
	}
	// 2. 获取当前登录用户（用于查询该用户的短链）
	user, err := auth.GetCurrentContextUser(c)
	if err != nil {
		// 未登录时重定向到登录页
		c.Redirect(http.StatusSeeOther, "/auth/loginPage?redirect=/url/list")
		return
	}
	c.HTML(http.StatusOK, "records.html", gin.H{
		"PageType": "records",
		"User":     user,
		"Page":     page,     // 当前页码
		"PageSize": pageSize, // 每页条数
	})
}

// UrlMapPageQuery 短链分页查询
func (rc ConvertUrlHandler) UrlMapPageQuery(c *gin.Context) {
	var req request.UrlMapPageMapRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
	}
	entities, total, _ := rc.urlQueryService.UrlMapPageQuery(c, req)
	var list []interface{}
	for _, entity := range entities {
		list = append(list, entity)
	}
	c.JSON(http.StatusOK, response.Success(&response.PageResult{
		Total: total,
		List:  list,
	}))
}

// UrlStatisticsPageQuery 短链转化统计
func (rc ConvertUrlHandler) UrlStatisticsPageQuery(c *gin.Context) {
	var req request.ShortUrlStatisticsRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
	}
	entities, total, _ := rc.urlQueryService.UrlStatistics(c, req)
	var list []interface{}
	for _, entity := range entities {
		list = append(list, entity)
	}
	c.JSON(http.StatusOK, response.Success(&response.PageResult{
		Total: total,
		List:  list,
	}))
}
